package com.yc.navy.springmvc.controller;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.yc.navy.springmvc.util.ConstantIfo;
import com.yc.navy.springmvc.vo.ResultVO;

@Controller
@RequestMapping()
public class SendCodeController {
	
	@GetMapping("/code")
	public void SendCode(HttpSession session, HttpServletResponse response) throws IOException {
		response.setHeader("paragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		
		String code = getRandomCode();
		session.setAttribute(ConstantIfo.LOGINCODE, code);
		
		//生成验证码图片
		BufferedImage image = getCodeImage(code, 98, 34);
		ImageIO.write(image, "JPEG", response.getOutputStream());
	}

	private BufferedImage getCodeImage(String code, int width, int height) {
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		
		//获取这个图片区域的绘笔
		Graphics g = image.getGraphics();
		
		// 绘制背景色
		g.setColor(getRandomColor(220, 30));
		
		// 用这个背景色绘制一个矩形
		g.fillRect(0, 0, width, height);
		
		//绘制干扰线
		int x1, y1, x2, y2;
		Random rd = new Random();
		for(int i = 0; i < 50; ++ i) {
			x1 = rd.nextInt(width);
			y1 = rd.nextInt(height);
			x2 = rd.nextInt(width);
			y2 = rd.nextInt(height);
		
			g.setColor(getRandomColor(150, 60));
			g.drawLine(x1, y1, x2, y2);
		}
		
		//绘制验证码
		char[] codes = code.toCharArray();
		g.setFont(new Font("Courier New", Font.ITALIC, 26));
		for(int i = 0, len = codes.length; i < len; ++ i) {
			g.setColor(getRandomColor(30, 110));
			g.drawString(String.valueOf(codes[i]), 10 + i * 20 , 24);
		}
		g.dispose();
		return image;
	}
	
	/**
	 * 生成随机验证码
	 * @return
	 */

	private String getRandomCode() {
		String str = "";
		Random rd = new Random();
		int flag;
		for(int i = 0; i < 4; ++ i) {
			flag = rd.nextInt(3);
		switch(flag) {
		case 0 : str += rd.nextInt(10); break;
		case 1 : str += (char)(rd.nextInt(26) + 65); break;
		case 2 : str += (char)( rd.nextInt(26) + 97); break;
		}
		}
		return str;
	}
	/**
	 * 生成随机颜色的
	 * @param start
	 * @param bound
	 * @return
	 */
	private Color getRandomColor(int start, int bound) {
		Random rd = new Random();
		int r = rd.nextInt(bound) + start;
		int g = rd.nextInt(bound) + start;
		int b = rd.nextInt(bound) + start;
		return new Color(r, g, b);
	}
}
